//
//  YBLoginVC.swift
//  Moonlight
//
//  Created by Penlon Kim on 2023/6/5.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON
import SVProgressHUD
import EachNavigationBar
import ATAuthSDK

class YBLoginVC: BaseVC {

    // MARK: Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()

        navigation.bar.alpha = 0
        view.backgroundColor = .lightWhiteDark27
        view.addSubview(loginView)

        loginView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

#if DEBUG
        vm.loginModel.userName = "18912341234"
        vm.loginModel.password = "123456Aa"
#endif

        //开始状态置为YES，默认当前环境可以使用一键登录
        TXCommonHandler.sharedInstance().accelerateVerify(withTimeout: 3.0) { resultDic in
            PPP("resultDic = \(resultDic)")
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.bk_setBackBarButtonItem(isHidden: true)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        loginView.endEditing(true)
    }

    // MARK: - lazy
    lazy var vm: YBLoginViewModel = {
        let vm = YBLoginViewModel()
        return vm
    }()

    private lazy var loginView: YBLoginView = {
        let view = YBLoginView()
        view.delegate = self
        return view
    }()

}

// MARK: - YBLoginViewDelegate代理
extension YBLoginVC: YBLoginViewDelegate {

    func loginViewDidClick(_ btnType: YBLoginView.BtnType) {
        switch btnType {
        case .login:
            loginView.endEditing(true)
            self.post_login()
        case .register:
            let vc = YBRegisterVC()
            self.navigationController?.pushViewController(vc)
        case .oneClickLogin:
            self.get_getToken()
        }
    }

    func loginViewInput(_ inputType: YBLoginRegisterInputView.InputType, content: String) {
        PPP("\(inputType.style.des): \(content)")
        switch inputType {
        case .phone:
            vm.loginModel.userName = content.removeAllSpace
        case .pwd:
            vm.loginModel.password = content.removeAllSpace
        case .code:
            break
        }
    }

}

// MARK: - 网络请求
extension YBLoginVC {

    fileprivate func post_login() {
        guard loginView.checkBtn.isSelected else {
            HintTool.toast("请勾选协议")
            return
        }
        guard let params = vm.validLoginParams({ msg in
            HintTool.toast(msg)
        }) else { return }

        SVProgressHUD.show(withStatus: "登录中...")
        vm.req_login(params) { ok, obj, msg, code in
            SVProgressHUD.dismiss()
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey].string else { return }
                HintTool.toast("登录成功")
                AppHelper.token = data

                TaskTool.delay(0.5) {
                    guard let window = UIApplication.shared.mainWindow() else { return }
                    AppHelper.startApp(window)
                }
            } else {
                HintTool.toast(msg)
            }
        }
    }

    fileprivate func post_clickLogin(token: String) {
        vm.req_clickLogin(token: token) { ok, obj, msg, code in
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey].string else { return }
                print(data)
            } else {
                HintTool.toast(msg)
            }
        }
    }

}

// MARK: - AlicomFusionAuthDelegate代理
extension YBLoginVC {
    func loginWithToken(maskToken: String) {
        // 拿到token去登录....
        SVProgressHUD.show(withStatus: "登录中...")
        vm.req_clickLogin(token: maskToken) { ok, obj, msg, code in
            SVProgressHUD.dismiss()
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey].string else { return }
                HintTool.toast("登录成功")
                AppHelper.token = data

                TaskTool.delay(0.5) {
                    guard let window = UIApplication.shared.mainWindow() else { return }
                    AppHelper.startApp(window)
                }
            } else {
                HintTool.toast(msg)
            }
        }
    }
}

// MARK: - 网络请求
extension YBLoginVC {

    fileprivate func get_getToken() {
        SVProgressHUD.show(withStatus: "一键登录启动中")
       let model = PNSBuildModelUtils.buildModel(with: PNSBuildModelStyle.PNSBuildModelStyleAlertPortrait, button1Title: "密码登录", target1: self, selector1: #selector(gotoSmsControllerAndShowNavBar), button2Title: "", target2: self, selector2: #selector(gotoSmsControllerAndHiddenNavBar))

        TXCommonHandler.sharedInstance().getLoginToken(withTimeout: 3.0, controller: self, model: model) { [self] resultDic in
            PPP("获取token resultDic = \(resultDic)")
            if let resultCode = resultDic["resultCode"] as? String {

                if resultCode == PNSCodeLoginControllerPresentSuccess {
                    PPP("授权页拉起成功回调 resultDic =  \(resultDic)")
                    SVProgressHUD.dismiss()
                }else if resultCode == PNSCodeLoginControllerClickCancel {
                    PPP("页面点击事件回调 resultDic = \(resultDic)")
                    TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
                }else if resultCode == PNSCodeSuccess {
                    PPP("获取LoginToken成功回调：\(resultDic)");
                    if let token = resultDic["token"] as? String {
                        // 去登录
                        loginWithToken(maskToken: token)
                        TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
                    }
                }else if resultCode == PNSCodeLoginControllerSuspendDisMissVC {
                    PPP("页面点击事件回调 resultDic = \(resultDic)")
                    TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
                }else {
                    SVProgressHUD.dismiss()
                    PPP("获取LoginToken或拉起授权页失败回调 resultDic = \(resultDic)");
                }
            }
        }
    }

    @objc func gotoSmsControllerAndShowNavBar() {
        TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
    }

    @objc func gotoSmsControllerAndHiddenNavBar() {
        TXCommonHandler.sharedInstance().cancelLoginVC(animated: true)
    }
}

